package com.qcu.task;

import com.qcu.service.PostFailLogService;
import com.qcu.service.PostService;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * @Name: MyComputer
 * @ClassName FailPostTask
 * @Description:
 * @date 2025/2/16 12:07
 */
@Service
@Slf4j
public class FailPostTask {
    @Resource
    PostService postService;
    @Resource
    PostFailLogService postFailLogService;
    @Resource
    JavaMailSender javaMailSender;

    @Value("${spring.mail.username}")
    private String from;
    //每小时执行一次
    @Scheduled(cron = "0 0 0/1 * * ?")
    // 每10秒执行一次
//    @Scheduled(cron = "0/10 * * * * ?")
    public void disposeFailPost() {
        log.info("开始执行Post发布失败反馈任务");
        List<String> emails = postFailLogService.getEmailOfFailPost();
        if (emails.size() != 0){
            // todo: 发送邮件
            // emails 转换为字符串数组
            String[] to = emails.toArray(new String[0]);
            SimpleMailMessage message = new SimpleMailMessage();
            message.setFrom(from);
            message.setTo(to);
            message.setSubject("帖子发布失败通知");
            message.setText("您的帖子发布失败,可能存在违规内容，已被审核人员拦截");
            javaMailSender.send(message);
            // 删除post_fail_log中数据
            postFailLogService.remove(null);
        }

    }
}
